package com.test.config;

import com.zaxxer.hikari.HikariDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@ComponentScans({
        @ComponentScan("com.test.service")
})
@MapperScan("com.test.dao")
@Configuration
@EnableTransactionManagement
public class RootConfiguration {
    @Bean
    public DataSource dataSource() {
        HikariDataSource dataSource=new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://192.168.43.114:3306/study");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

    //去掉mybatis的xml配置必须必须存在SqlSessionTemplate或是SqlSessionFactoryBean的Bean，否则会无法初始化（毕竟要数据库的链接信息）
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(@Autowired DataSource dataSource) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean;

    }
    @Bean
    public TransactionManager transactionManager(@Autowired DataSource dataSource){
         return new DataSourceTransactionManager(dataSource);
    }
}
